#include "SPIFFS.h"
#include <Arduino.h>

void setup() {
  Serial.begin(115200);
  while (!Serial);

  Serial.println("Initializing SPIFFS");

  if (!SPIFFS.begin(true)) {
    Serial.println("An error occurred while mounting SPIFFS");
    return;
  }
  Serial.println("SPIFFS mounted successfully");

  // 获取SPIFFS分区信息
  Serial.print("Total space: ");
  Serial.print(SPIFFS.totalBytes());
  Serial.println(" bytes");
  Serial.print("Used space: ");
  Serial.print(SPIFFS.usedBytes());
  Serial.println(" bytes");

  // 写入文件
  File file = SPIFFS.open("/hello.txt", FILE_WRITE);
  if (!file) {
    Serial.println("Error opening file for writing");
    return;
  }
  if (file.println("Hello, World!")) {
    Serial.println("File written");
  } else {
    Serial.println("Write failed");
  }
  file.close();

  // 读取文件
  file = SPIFFS.open("/hello.txt", FILE_READ);
  if (!file) {
    Serial.println("Error opening file for reading");
    return;
  }
  Serial.print("Read from file: ");
  while (file.available()) {
    Serial.write(file.read());
  }
  file.close();

  // 删除文件
  if (SPIFFS.remove("/hello.txt")) {
    Serial.println("File deleted");
  } else {
    Serial.println("Delete failed");
  }

  // 结束使用SPIFFS
  SPIFFS.end();
  Serial.println("SPIFFS ended");
}

void loop() {
  // 这里可以留空，因为我们只需要在setup中执行一次测试
}    